import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, logout as logoutApi, getUserInfo } from '../api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const isLoggedIn = ref(!!token.value)

  // 登录
  const login = async (username, password) => {
    try {
      const data = await loginApi({ username, password })
      token.value = data.token
      userInfo.value = data.user
      isLoggedIn.value = true
      
      // 保存token到localStorage
      localStorage.setItem('token', data.token)
      
      return { success: true, data }
    } catch (error) {
      return { success: false, error }
    }
  }

  // 登出
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出API调用失败:', error)
    } finally {
      // 清除本地数据
      token.value = ''
      userInfo.value = null
      isLoggedIn.value = false
      localStorage.removeItem('token')
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const data = await getUserInfo()
      userInfo.value = data
      return { success: true, data }
    } catch (error) {
      // token失效，清除登录状态
      await logout()
      return { success: false, error }
    }
  }

  // 检查是否是管理员
  const isAdmin = () => {
    return userInfo.value && (userInfo.value.is_staff || userInfo.value.is_superuser)
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    fetchUserInfo,
    isAdmin
  }
}, {
  persist: true // 持久化存储
})

